package org.omich.loaves;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;

import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.os.Message;

public class BluetoothBrainClient /*extends BluetoothMessageGetter*/ implements IBrainClient {
	private IMessageHandler mMessageHandler = new IMessageHandler() {
		public void handle(Object object) {
			if (object instanceof LoavesStatus)
				mGettingStatusHandler.handle((LoavesStatus)object);
		}
	};
	
	private IGettingsStatusHandler mGettingStatusHandler;
	
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LoavesActivity.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                Object ob;
                try {
                	ob = new ObjectInputStream(new ByteArrayInputStream(readBuf)).readObject();
                	mMessageHandler.handle(ob);
				} catch (OptionalDataException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (StreamCorruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
    };

	private INetworkTransport mTransport;
	
	BluetoothBrainClient(INetworkTransport transport) {
		mTransport = transport;
		transport.SetMessageProcessorHandler(mHandler);
		//setHandler(mHandler);
	}
   
	@Override
	public void tryToEatLoaf(String playerName, int loafNumber) {
		mTransport.SendMessage(new TryEatingMessage(playerName, loafNumber));
	}

	@Override
	public void getStatus(IGettingsStatusHandler... arg0) {
		mGettingStatusHandler = arg0[0];
		mTransport.SendMessage(new GetStatusMessage());
	}

	@Override
	public String getPlayerName() {
		return mTransport.getName();
	}

	@Override
	public void newGame(int loavesAmount, int maxWeight) {
		// TODO
		// TODO Auto-generated method stub
	}
	
	public void connectToServer( BluetoothDevice device) {
	}
}
